﻿/*
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2009
' by DotNetNuke Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
*/

using System;
using Gallio.Framework;
using MbUnit.Framework;
using DotNetNuke.Tests.UI.WatiN.Common;
using DotNetNuke.Tests.UI.WatiN.Utilities;
using DotNetNuke.Tests.UI.WatiN.Common.WatiNObjects;
using System.IO;
using System.Text.RegularExpressions;

namespace DotNetNuke.Tests.UI.WatiN.BuildVerification
{
    [TestFixture]
    [DependsOn(typeof(InstallTests))]
    [DependsOn(typeof(UpgradeTests))]
    [DependsOn(typeof(LoginTests))]
    public class HostSettingsTests : BVTBase
    {
        #region Test Setup and TearDown

        [SetUp]
        public void SetUp()
        {
            SetUpTest();
        }

        [TearDown]
        public void TearDown()
        {
            TearDownTest();
        }

        #endregion

        #region Tests

        [Test]
        [CsvData(ResourcePath = "TestData.UpgradeList.csv", HasHeader = true)]
        [CsvData(ResourcePath = "TestData.InstallList.csv", HasHeader = true)]
        public void Configure_Email(string version, string type)
        {
            if (type.Equals("UpgradeOnly"))
            {
                TestLog.WriteLine("This test has not been run on an installation site.");
                Assert.IsTrue(true);
            }
            else if (type.Equals("InstallOnly"))
            {
                TestLog.WriteLine("This test has not been run on an upgraded site.");
                Assert.IsTrue(true);
            }
            else
            {
                //Arrange                
                string capturePath = CapturePath + @"\HostSettingsTests\ConfigureEmail\";
                if (!Directory.Exists(capturePath))
                {
                    Directory.CreateDirectory(capturePath);
                }
                WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
                LoginPage loginPage = new LoginPage(homePage);
                //Delete any files in the test EmailAddress folder
                homePage.DeleteFilesInTestEmails();

                //Edit the web.config file so that Emails are sent to a local folder
                WebConfigManager.UpdateConfig(PhysicalPath);

                try
                {
                    loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
                    //Assert.IsFalse(homePage.PageContainsErrors());
                    ieInstance.GoTo(SiteURL + "/tabid/16/portalid/0/Default.aspx");
                    if (homePage.PageContainsErrors())
                    {
                        //Take a screen Capture
                        ieInstance.CaptureWebPageToFile(CapturePath + "/ErrorOnHostSettingsPage.jpg");
                        TestLog.WriteHighlighted("WARNING:");
                        TestLog.WriteLine("An error occurred on the Host Settings Page, view the corresponding screen shot and exception text log for more information on the error. ");

                        //Record any recent exceptions in the log
                        ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
                        HostSQLPage SQLPage = new HostSQLPage(homePage);
                        SQLPage.CheckForRecentExceptionsWriteToFile(CapturePath + "HostSettingsExceptions.txt", SiteType.Equals("Qualifier"));

                        //Continue the test
                        ieInstance.GoTo(SiteURL + "/tabid/16/portalid/0/Default.aspx");
                    }
                    HostSettingsPage hostSettings = new HostSettingsPage(homePage);

                    //Act
                    hostSettings.HostEmailTextField.Value = "test@dnn.com";
                    hostSettings.AdvancedSettingsTab.Click();
                    System.Threading.Thread.Sleep(1500);
                    hostSettings.SMTPServerField.Value = "localhost"; 
                    hostSettings.SMTPAnonymousAuthenticationRadioButton.Checked = true;
                    System.Threading.Thread.Sleep(1000);
                    hostSettings.SMTPTestLink.ClickNoWait();
                    System.Threading.Thread.Sleep(2000);

                    //Assert
                    if (homePage.PageContainsErrors())
                    {
                        //Take a screen Capture
                        ieInstance.CaptureWebPageToFile(CapturePath + "/ErrorOnHostSettingsPage.jpg");
                        TestLog.WriteHighlighted("WARNING:");
                        TestLog.WriteLine("An error occurred on the Host Settings Page, view the corresponding screen shot and exception text log for more information on the error. ");

                        //Record any recent exceptions in the log
                        ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
                        HostSQLPage SQLPage = new HostSQLPage(homePage);
                        SQLPage.CheckForRecentExceptionsWriteToFile(CapturePath + "HostSettingsExceptions.txt", SiteType.Equals("Qualifier"));
                    }
                    Assert.IsTrue(Directory.GetFiles(TestEmailPath).Length > 0);
                    Assert.IsFalse(string.IsNullOrEmpty(Directory.GetFiles(TestEmailPath)[0]));

                    //Check for the change password EmailAddress
                    String emailFileName = null;
                    String emailContent = null;
                    int emailFilePosition = 0;
                    for (int i = 0; i < Directory.GetFiles(TestEmailPath).Length; i++)
                    {
                        emailFileName = Directory.GetFiles(TestEmailPath)[i];
                        emailContent = File.ReadAllText(emailFileName);
                        if (emailContent.Contains("X-Receiver: test@dnn.com") && emailContent.Contains("X-Sender: test@dnn.com"))
                        {
                            emailFilePosition = i;
                        }
                    }

                    emailFileName = Directory.GetFiles(TestEmailPath)[emailFilePosition];
                    emailContent = File.ReadAllText(emailFileName);
                    //Separate the EmailAddress subject from the EmailAddress information
                    //string contentLineRegex = "(?<=Subject:).*";
                    //Match match = Regex.Match(@emailContent, contentLineRegex);
                    //Assert.IsTrue(match.Success, "Could not find subject Line! Looking in file: " + emailFileName);

                    //Convert the EmailAddress content
                    String emailSubject = ConvertEmailSubjectFromBase64ToUnicode(emailContent, emailFileName);
                    Assert.IsTrue(emailSubject.Contains("DotNetNuke SMTP Configuration Test"), "Looking at string: " + emailSubject);

                    //Delete The Email file 
                    File.Delete(Directory.GetFiles(TestEnvironment.TestEmailPath)[0]);
                }
                catch (Exception e)
                {
                    if (!e.ToString().Contains("AssertionFailureException"))
                    {
                        ieInstance.CaptureWebPageToFile(capturePath + "Exception.jpg");
                        Assert.IsTrue(false, "An Exception Occured during the test, view the screen shot for more information. " + System.Environment.NewLine + e.ToString());
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
        }

        [Test]
        [CsvData(ResourcePath = "TestData.UpgradeList.csv", HasHeader = true)]
        [CsvData(ResourcePath = "TestData.InstallList.csv", HasHeader = true)]
        public void Check_Correct_Ribbon_Bar_Behaviour(string version, string type)
        {
            if (type.Equals("UpgradeOnly"))
            {
                Gallio.Framework.TestLog.WriteLine("This test has not been run on an installation site.");
                Assert.IsTrue(true);
            }
            else if (type.Equals("InstallOnly"))
            {
                Gallio.Framework.TestLog.WriteLine("This test has not been run on an upgraded site.");
                Assert.IsTrue(true);
            }
            else
            {
                //Arrange
                string capturePath = CapturePath + @"\HostSettingsTests\CheckCorrectRibbonBarBehaviour\";
                WatiNAssert watinAssert = new WatiNAssert(ieInstance, capturePath);
                if (!Directory.Exists(capturePath))
                {
                    Directory.CreateDirectory(capturePath);
                }
                WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
                LoginPage loginPage = new LoginPage(homePage);
                try
                {
                    loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
                    //Assert.IsFalse(homePage.PageContainsErrors());
                    ieInstance.GoTo(SiteURL + "/tabid/16/portalid/0/Default.aspx");
                    if (homePage.PageContainsErrors())
                    {
                        //Take a screen Capture
                        ieInstance.CaptureWebPageToFile(CapturePath + "/ErrorOnHostSettingsPage.jpg");
                        TestLog.WriteHighlighted("WARNING:");
                        TestLog.WriteLine("An error occurred on the Host Settings Page, view the corresponding screen shot and exception text log for more information on the error. ");

                        //Record any recent exceptions in the log
                        ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
                        HostSQLPage SQLPage = new HostSQLPage(homePage);
                        SQLPage.CheckForRecentExceptionsWriteToFile(CapturePath + "HostSettingsExceptions.txt", SiteType.Equals("Qualifier"));

                        //Continue the test
                        ieInstance.GoTo(SiteURL + "/tabid/16/portalid/0/Default.aspx");
                    }
                    HostSettingsPage hostSettings = new HostSettingsPage(homePage);
                    //hostSettings.OtherSettingsExpandButton.Click();
                    hostSettings.AdvancedSettingsTab.Click();

                    if (version.Equals(""))
                    {
                        //Test is running on an install site
                        watinAssert.AssertIsTrue(homePage.ControlPanelElement.Id.Contains(homePage.RibbonBarID), "Error1.jpg");
                        //watinAssert.AssertIsTrue(homePage.GetSelectedItemFromSelecList(hostSettings.ControlPanelStyleSelectList).ToString().Equals("RIBBONBAR"), "Error2.jpg", homePage.GetSelectedItemFromSelecList(hostSettings.ControlPanelStyleSelectList).ToString());
                        watinAssert.AssertIsTrue(hostSettings.ControlPanelStyleSelectList.SelectedOption.ToString().Equals("RIBBONBAR"), "Error2.jpg", hostSettings.ControlPanelStyleSelectList.SelectedOption.ToString());
                        watinAssert.AssertIsTrue(hostSettings.ControlPanelStyleSelectList.Option("ICONBAR").Exists, "Error3.jpg");   
                    }

                    else
                    {
                        //Test is running on an upgrade site
                        int versionNum = Convert.ToInt32(version.Replace(".", ""));
                        if (versionNum < 50400)
                        {
                            if (type.Contains("Pro") && versionNum > 50300)
                            {
                                watinAssert.AssertIsTrue(homePage.ControlPanelElement.Id.Contains(homePage.RibbonBarID), "Error1.jpg");
                                watinAssert.AssertIsTrue(hostSettings.ControlPanelStyleSelectList.SelectedOption.ToString().Equals("RIBBONBAR"), "Error2.jpg");
                                //watinAssert.AssertIsTrue(homePage.GetSelectedItemFromSelecList(hostSettings.ControlPanelStyleSelectList).ToString().Equals("RIBBONBAR"), "Error2.jpg");
                       
                            }
                            else
                            {
                                watinAssert.AssertIsFalse(homePage.ControlPanelElement.Id.Contains(homePage.RibbonBarID), "Error1.jpg");
                                watinAssert.AssertIsFalse(hostSettings.ControlPanelStyleSelectList.SelectedOption.ToString().Equals("RIBBONBAR"), "Error2.jpg");
                                //watinAssert.AssertIsTrue(homePage.GetSelectedItemFromSelecList(hostSettings.ControlPanelStyleSelectList).ToString().Equals("ICONNBAR"), "Error2.jpg");
                       
                            }
                        }
                        else
                        {
                            watinAssert.AssertIsTrue(homePage.ControlPanelElement.Id.Contains(homePage.RibbonBarID), "Error1.jpg");
                            watinAssert.AssertIsTrue(hostSettings.ControlPanelStyleSelectList.SelectedOption.ToString().Equals("RIBBONBAR"), "Error2.jpg");
                            //watinAssert.AssertIsTrue(homePage.GetSelectedItemFromSelecList(hostSettings.ControlPanelStyleSelectList).ToString().Equals("RIBBONBAR"), "Error2.jpg");
                        }

                        watinAssert.AssertIsTrue(hostSettings.ControlPanelStyleSelectList.Option("RIBBONBAR").Exists, "Error3.jpg");
                        watinAssert.AssertIsTrue(hostSettings.ControlPanelStyleSelectList.Option("ICONBAR").Exists, "Error4.jpg");
                    }
                }
                catch (Exception e)
                {
                    if (!e.ToString().Contains("AssertionFailureException"))
                    {
                        ieInstance.CaptureWebPageToFile(capturePath + "Exception.jpg");
                        Assert.IsTrue(false, "An Exception Occured during the test, view the screen shot for more information. " + Environment.NewLine + e);
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
        }
        
        #endregion

        private string ConvertEmailSubjectFromBase64ToUnicode(string emailContent, string emailFileName)
        {
            //Separate the EmailAddress subject from the EmailAddress information
            string contentLineRegex = "(?<=Subject:).*";
            Match match = Regex.Match(@emailContent, contentLineRegex);
            Assert.IsTrue(match.Success, "Could not find subject Line! Looking in file: " + emailFileName);

            //Convert the EmailAddress content
            emailContent = match.Value;
            emailContent = emailContent.Replace(" ", "");
            emailContent = emailContent.Replace("=?utf-8?B?", "");
            emailContent = emailContent.Replace("?=", "");
            byte[] b = null;
            try
            {
                b = Convert.FromBase64String(emailContent);
            }
            catch (Exception e)
            {
                Gallio.Framework.TestLog.Write("Exception while converting from base 64: " + emailContent + Environment.NewLine + e);
            }
            String decodedEmailSubject = System.Text.ASCIIEncoding.ASCII.GetString(b);
            return decodedEmailSubject;
        }


    }
}

